<?php
/**
 * @see Alinks_Post_Scraper_Interface
 */
require_once('Alinks/Post/Scraper/Interface.php');

/**
 * Abstract class for the scraper classes
 *
 * Copyright (C) 2008  Sean Hickey
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Sean Hickey <sean@headzoo.com>
 * @version $Id: Abstract.php 404 2008-07-05 03:04:23Z sean $
 * @package Alinks_Post
 */
abstract class Alinks_Post_Scraper_Abstract implements Alinks_Post_Scraper_Interface
{
	/**
	 * Scrapes a post for in-post defined keyphrases
	 *
	 * Looks for anchor tags that have the alinks="save" attribute. When found,
	 * the link is turned into a keyphrase.
	 *
	 * @param int $post_id The post ID
	 * @return int
	 */
	public function scrape($post_id)
	{
		$post_id = (int)$post_id;
		$wpdb = Alinks_Registry::get('wpdb');
		$sql = "SELECT post_content FROM $wpdb->posts WHERE ID = $post_id LIMIT 1";
		$post = $wpdb->get_row($sql);
		if (stristr($post->post_content, '<alinks') !== false) {
			$keeper = Alinks_Registry::get('Alinks_Keyphrase_Keeper');
			
			$matches = array();
			$href_matches = array();
			$title_matches = array();
			preg_match_all('%<alinks(.*?)>(.*?)</alinks>%', $post->post_content, $matches);
			for($i = 0, $t = count($matches[0]); $i < $t; $i++) {
				if (!preg_match('/href\\s?=\\s?["|\'](.*?)["|\']/', $matches[1][$i], $href_matches)) {
					continue;
				}
				
				$href = $href_matches[1];
				$title = null;
				if (preg_match('/title\\s?=\\s?["|\'](.*?)["|\']/', $matches[1][$i], $title_matches)) {
					$title = $title_matches[1];
				}
				
				$keyphrase = $keeper->create('default');
				$keyphrase->setPhrase($matches[2][$i]);
				$keyphrase->setDescription($title);
				$keyphrase->addOption('url', $href);
				
				$post->post_content = str_replace($matches[0][$i], $matches[2][$i], $post->post_content);
			}
		
			$post->post_content = $wpdb->escape($post->post_content);
			$sql = "UPDATE $wpdb->posts SET post_content = '$post->post_content' WHERE ID = $post_id LIMIT 1";
			$wpdb->query($sql);
			add_action('admin_notices', array($this, 'adminNotices'));
		}
		
		return $post_id;
	}
}